//
//  ThreadsViewController.m
//  ViewPoint
//
//  Created by Demiao Lin on 10/20/08.
//  Copyright 2008 Tsinghua. All rights reserved.
//

#import "ThreadsViewController.h"
#import "PostViewController.h"
#import "ThreadViewController.h"
#import "NewSMTH.h"

#define INDICATOR_VIEW	999
#define TOOLBAR_VIEW	998
#define UPDATEINTERVAL	120

@implementation ThreadsViewController

@synthesize threads;
@synthesize postViewController;
@synthesize threadViewController;
@synthesize board;
@synthesize page_num;
@synthesize tableView;

- (id)init{
	if( (self=[super init]) != nil ){
		PostViewController *onePostViewController = [[PostViewController alloc] init];
		self.postViewController = onePostViewController;
		[onePostViewController release];
		
		ThreadViewController *oneThreadViewController = [[ThreadViewController alloc] init];
		self.threadViewController = oneThreadViewController;
		[oneThreadViewController release];
	}
	return self;
}

- (id) initWithTitle: (NSString *) title {
	if( (self=[self init]) != nil ){
		[self setTitle:title];
	}
	return self;
}

- (void) setTitle:(NSString *) title 
			board:(Board *) b{
    if(self.board && b && self.board.bid==b.bid){
        
    }else{
        [self setTitle:title];
        [self setBoard:b];
        
		self.page_num = 0;
		lastUpdateTime = CFAbsoluteTimeGetCurrent();
		
        self.threads = nil;
        [self.tableView reloadData];
    }
}

- (void)loadView
{
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
	UIView *mainView = [[UIView alloc] initWithFrame:rect];
	self.view = mainView;
	[mainView release];
	
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    rect.size.height = 44.0f;
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:rect];
    UIView *tableFooterView = [[UIView alloc] initWithFrame:rect];
	UITableView *oneTableView = [[UITableView alloc] initWithFrame:rect
                                                             style:UITableViewStylePlain];
	oneTableView.tableHeaderView = tableHeaderView;
    oneTableView.tableFooterView = tableFooterView;
    [tableHeaderView release];
    [tableFooterView release];
    
    [oneTableView setEditing:NO animated:YES];
    [oneTableView setAutoresizingMask: (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth)];
    [oneTableView setDelegate: self];
    [oneTableView setDataSource: self];
    self.tableView = oneTableView;
	[self.view addSubview:oneTableView];
    [oneTableView release];
	
	[self loadToolbar];
    
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
	//[activityIndicator setCenter:CGPointMake(rect.size.width/2, rect.size.height/2)];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
	activityIndicator.tag = INDICATOR_VIEW;
    [self.view addSubview:activityIndicator];
    [activityIndicator release];
    
    //[self setViewsRotation];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    //[self showLoadingIndicators];
    [self setViewsRotation];
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    [activityIndicator startAnimating];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	[self loadTableView];
}


- (void)didFinishLoadingWithData:(ArrayAndPageNum *)data
{
    if(data!=nil){
        self.threads = data.array;
        self.page_num = data.page_num;
        [self.tableView reloadData];
        [self.tableView flashScrollIndicators];
    }
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    [activityIndicator stopAnimating];
}

-(void) loadTableViewData:(id)object{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	ArrayAndPageNum *data = [[[[NewSMTH alloc] init] autorelease] getThreadsWithBoardName:[self.board bname]  page_num:self.page_num];
	//threads = data.array;
    
	//NSLog(@"thread length:%d", [threadsArray count]);
	//[self performSelectorOnMainThread:@selector(didFinishLoadingWithData:) withObject:data waitUntilDone:NO];
	[self didFinishLoadingWithData:data];
	lastUpdateTime = CFAbsoluteTimeGetCurrent();
	[pool release];
}


-(void) loadTableView{
    CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent(); 
	if(self.threads==nil || [self.threads count]==0 || currentTime-lastUpdateTime>UPDATEINTERVAL){
		UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
		[activityIndicator startAnimating];
		[self performSelectorInBackground:@selector(loadTableViewData:) withObject:nil];
		//[NSThread detachNewThreadSelector:@selector(loadTableViewData:) toTarget:self withObject:nil];
	}
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(self.threads){
        return [self.threads count];
    }else{
        return 0;
    }
}


- (UITableViewCell *)tableView:(UITableView *)onetableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Thread *thread = [self.threads objectAtIndex:[indexPath row]];
    //NSString *CellIdentifier = [NSString stringWithFormat:@"Threads_%d_%d", [board bid], [thread tid]];
    NSString *CellIdentifier = @"ThreadsCell";
    
    UITableViewCell *cell = [onetableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		//[cell release];
	}
    cell.text = [thread title];
    return cell;
}

- (void)loadToolbar {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
    NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:9];
	
	UIBarButtonItem *flexibleSpaceItem;
    
    /*
	 flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
	 target:nil 
	 action:NULL] autorelease];	
	 [buttons addObject:flexibleSpaceItem];
	 [flexibleSpaceItem release];
	 */
	
	UIBarButtonItem *item;
	item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"prePage.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(loadPreviousPage:)] autorelease];
	[buttons addObject:item];
	
    flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
    
	/*
	 UILabel *pageLabel = [[UILabel alloc] init];
	 pageLabel.textAlignment = UITextAlignmentLeft;
	 pageLabel.font = [UIFont boldSystemFontOfSize:18];
	 pageLabel.text = [NSString stringWithFormat:@"[%d]", self.page_num];
	 
	 [buttons addObject:pageLabel];
	 [pageLabel release];
	 */
	
    /*
	item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"thread.png"]
                                             style:UIBarButtonItemStylePlain
                                            target:self
                                            action:@selector(loadNextPage:)] autorelease];
	[buttons addObject:item];
	
	
    flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
    */
    
    item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nextPage.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(loadNextPage:)] autorelease];
	[buttons addObject:item];
	
	
	/*
	 flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
	 target:nil 
	 action:NULL] autorelease];	
	 [buttons addObject:flexibleSpaceItem];
	 */
	
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
	UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:rect];
	//toolbar.barStyle = UIBarStyleBlackOpaque;
    toolbar.barStyle = UIBarStyleBlackTranslucent;
	[toolbar setItems:buttons animated:YES];
    [buttons release];
    toolbar.tag = TOOLBAR_VIEW;
	//[toolbar sizeToFit];
    
	//self.navigationItem.titleView = toolbar;
    [self.view setUserInteractionEnabled:YES];
	[self.view addSubview:toolbar];
    [toolbar release];
	
	[pool release];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	Thread *thread = [self.threads objectAtIndex:[indexPath row]];
    /*
	[postViewController setPostViewWithTitle:[thread title] board:self.board post_id:[thread tid] post_type:@"no"];
	[[self navigationController] pushViewController:self.postViewController animated:YES];
	//[postViewController hideToolbarAndNavBar];
    */
    
	[threadViewController setThreadViewWithTitle:[thread title] board:self.board thread_id:[thread tid] post_id:[thread tid]];
	[[self navigationController] pushViewController:self.threadViewController animated:YES];
}

-(void) loadPreviousPage:(id)sender{
	self.page_num -= 1;
	lastUpdateTime = 0;
    [self loadTableView];
}
-(void) loadNextPage:(id)sender{
	self.page_num += 1;
	lastUpdateTime = 0;
    [self loadTableView];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}

- (void) willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation) fromOrientation duration:(NSTimeInterval) duration{
    [self setViewsRotation];
}

- (void) setViewsRotation {
	UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    
    UIInterfaceOrientation orientation = self.interfaceOrientation;
    if(orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight){
        [tableView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 300.0f)];
        [tableView.tableHeaderView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 32.0f)];
		[toolbar setFrame:CGRectMake(0.0f, 300.0f-44.0f, 480.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(240, 140)];
	}else{
		[tableView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
        [tableView.tableHeaderView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
        [toolbar setFrame:CGRectMake(0.0f, 460.0f-44.0f, 320.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(160, 220)];
	}
	[self.view bringSubviewToFront:toolbar];
	[self.view bringSubviewToFront:activityIndicator];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)dealloc {
	[threads release];
	[postViewController release];
	[threadViewController release];
	[tableView release];
    [super dealloc];
}


@end

